package org.xmx0632.connector.initalizer;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.xmx0632.connector.codec.AesMessageDecoder;
import org.xmx0632.connector.codec.JsonMessageDecoder;
import org.xmx0632.connector.codec.JsonMessageEncoder;
import org.xmx0632.connector.handlers.MessageProcessHandler;
import org.xmx0632.connector.handlers.PreMessageProcessHandler;
import org.xmx0632.connector.handlers.TimeoutServerHandler;
import org.xmx0632.connector.protocol.message.Response;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class BaseProtocolInitalizer extends ChannelInitializer<SocketChannel> {

	private static final int READ_IDEL_TIME_OUT = 3600; // 读超时(秒)
	private static final int WRITE_IDEL_TIME_OUT = 0;// 写超时
	private static final int ALL_IDEL_TIME_OUT = 0; // 所有超时

	@Autowired
	StringDecoder stringDecoder;

	@Autowired
	JsonMessageDecoder jsonMessageDecoder;

	@Autowired
	JsonMessageEncoder jsonMessageEncoder;

	@Autowired
	StringEncoder stringEncoder;

	@Autowired
	AesMessageDecoder aesMessageDecoder;

	@Autowired
	TimeoutServerHandler timeoutServerHandler;

	@Autowired
	PreMessageProcessHandler preMessageProcessHandler;

	@Autowired
	MessageProcessHandler<? extends Response> messageProcessHandler;

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();

		setupBasePipeline(pipeline, false);
	}

	protected void setupBasePipeline(ChannelPipeline pipeline, boolean isAesServer) {
		// 都属于ChannelIntboundHandler，按照顺序执行
		// 超时检测
		pipeline.addLast(
				new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS));
		pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
		pipeline.addLast("stringDecoder", stringDecoder);
		// aes decode
		if (isAesServer) {
			pipeline.addLast("aesMessageDecoder", aesMessageDecoder);
		}
		pipeline.addLast("jsonMessageDecoder", jsonMessageDecoder);

		// 业务逻辑
		pipeline.addLast("timeoutHandler", timeoutServerHandler);
		pipeline.addLast("preMessageProcessHandler", preMessageProcessHandler);
		pipeline.addLast("messageProcessHandler", messageProcessHandler);

		// 都属于ChannelIntboundHandler，按照逆序执行
		pipeline.addLast("stringEncoder", stringEncoder);
		pipeline.addLast("jsonMessageEncoder", jsonMessageEncoder);
	}

}
